<template>
  <el-dialog
    v-el-drag-dialog
    title="新增退货单"
    :visible.sync="visible"
    width="1024px"
    @closed="reset"
  >
    <el-form ref="dataForm" :rules="rules" class="form" :model="temp" label-position="right" label-width="100px" style="margin: 0 50px;">
      <el-form-item label="退货单位:" prop="orgName">
        <el-input v-model="temp.orgName" disabled />
      </el-form-item>
      <el-form-item label="退货人:" prop="operatorId">
        <el-select v-model="temp.operatorId" :loading="$loadingPlugin.getOwnersList" filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退货时间:" prop="returnTime">
        <el-input v-model="temp.returnTime" disabled />
      </el-form-item>
      <el-form-item label="关联订单号:" prop="orderCode">
        <el-input v-model="temp.orderCode" disabled />
      </el-form-item>
      <el-form-item label="客户名称:" prop="csmName">
        <el-input v-model="temp.csmName" disabled />
      </el-form-item>
      <el-form-item label="联系电话:" prop="csmPhone">
        <el-input v-model="temp.csmPhone" disabled />
      </el-form-item>
      <el-form-item label="地址:" prop="csmAddress" class="block">
        <el-input v-model="temp.csmAddress" disabled />
      </el-form-item>
      <el-form-item label="退货原因:" prop="remark" class="block">
        <el-input v-model="temp.remark" />
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :height="300"
      :immediate-fetch="false"
      :summary-method="getSummaries"
      show-summary
      @fetch="fetchData"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        申请退货
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    queryGoodsBack,
    queryOwnerList,
    queryBackGoodsOrderDetail
  } from '@/api'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import { formatColumnMap } from '@/utils'

  export default {
    name: 'back-goods',
    data() {
      return {
        visible: false,
        ownersList: [],
        temp: {
          orgName: '',
          operatorId: '',
          returnTime: '',
          orderCode: '',
          csmName: '',
          csmPhone: '',
          csmAddress: '',
          remark: ''
        },
        orderBillInfo: {},
        specList: [],
        rules: {
          orgName: [{ required: true, message: '请选择退货单位', trigger: 'change' }],
          operatorId: [{ required: true, message: '请选择退货人', trigger: 'change' }],
          returnTime: [{ required: true, message: '请选择退货时间', trigger: 'change' }],
          csmId: [{ required: true, message: '请选择客户', trigger: 'change' }],
          csmAddress: [{ required: true, message: '请选择地址', trigger: 'change' }]
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'goodsName',
              label: '商品名称'
            },
            {
              prop: 'specCode',
              label: '规格型号',
              render: (h, { row }) => <span>{ row.specCode && formatColumnMap(this.specList, 'specCode', row.specCode, 'specName') }</span>
            },
            {
              prop: 'goodsCount',
              label: '数量',
              align: 'right'
            },
            {
              prop: 'netWeight',
              label: '净重',
              align: 'right'
            },
            {
              prop: 'price',
              label: '单价',
              align: 'right'
            },
            {
              prop: 'amount',
              label: '退货金额',
              align: 'right'
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'corpSettingData', 'orgList'
      ])
    },
    methods: {
      async open(temp) {
        await Promise.all([this.fetchData(temp), this.getOwnersList(temp.orgId)])
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp, {
              returnTime: moment().format('YYYY-MM-DD HH:mm')
            })
            this.temp.operatorId = temp.operatorId || temp.ownerId
          }
        })
      },
      async fetchData(temp) {
        const res = await queryBackGoodsOrderDetail({ orderCode: temp.orderCode })
        this.orderBillInfo = JSON.parse(res.data.orderBillInfo)
        const detailList = JSON.parse(res.data.orderBillInfo).detailList
        this.tableData.data = detailList.map(item => {
          return {
            ...item,
            amount: item.accReceivable.toFixed(2),
            goodsCount: item.gcount,
            price: (item.gprince || 0) - (item.gprefPrice || 0)
          }
        })
        this.specList = JSON.parse(res.data.specList)
      },
      // 查询退货人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'netWeight' || column.property === 'price') {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        sums[sums.length - 1] = Number(sums[sums.length - 1]).toFixed(2)
        return sums
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const orgInfo = this.orgList.find(item => item.orgId === this.temp.orgId)
          const params = {
            orderCode: this.temp.orderCode,
            orgName: orgInfo.orgName,
            orgSNNo: orgInfo.orgSNNo,
            orgId: orgInfo.orgId,
            returnTime: moment(this.temp.returnTime).format(),
            operator: this.ownersList.find(item => item.userId === this.temp.operatorId).userName,
            operatorId: this.temp.operatorId,
            csmId: this.temp.csmId,
            csmCode: this.temp.csmCode,
            csmName: this.temp.csmName,
            csmPhone: this.temp.csmPhone,
            csmAddress: this.temp.csmAddress,
            remark: this.temp.remark,
            recycleDetailList: this.tableData.data
          }
          this.submit(params)
        })
      },
      async submit(params) {
        await queryGoodsBack(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功!',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.temp = {
          orgName: '',
          operatorId: '',
          returnTime: moment().format('YYYY-MM-DD HH:mm'),
          orderCode: '',
          csmName: '',
          csmPhone: '',
          csmAddress: '',
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
